package com.flanz.apache.velocity.uimocker;

import org.apache.velocity.app.event.implement.IncludeRelativePath;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * MyIncludeRelativePath.
 * 
 * @author cf
 * 
 */

public class MyIncludeRelativePath extends IncludeRelativePath {

	private static Logger LOG = LoggerFactory
			.getLogger(MyIncludeRelativePath.class);

	@Override
	public String includeEvent(final String includeResourcePath,
			final String currentResourcePath, final String directiveName) {
		String result = includeResourcePath;
		System.out.println("IN:(" + directiveName + ")" + includeResourcePath);
		int lastIndexOf = includeResourcePath.lastIndexOf("?");
		String jsonExtraName = null;

		// cut out URL arguments in parser include statement
		if (lastIndexOf != -1) {
			result = includeResourcePath.substring(0, lastIndexOf);
		}

		// extract extra arguments
		if (lastIndexOf != -1) {
			jsonExtraName = includeResourcePath.substring(lastIndexOf + 1);
		}

		StringBuilder sb = new StringBuilder();
		String[] split = result.split("/");
		for (int i = 0; i < split.length; i++) {
			if (!(i + 1 < split.length && ((split[i + 1].equalsIgnoreCase(".."))))
					&& !split[i].equalsIgnoreCase("..")) {
				sb.append('/');
				sb.append(split[i]);
			}
		}
		result = sb.toString();

		// Apply extra argument if exist.
		// handle selection-pattern-dynamic.interiorcolors.json Stuff
		if (jsonExtraName != null) {
			result = VmGeneratorMain.makePartVmKey(jsonExtraName, result);
			// add magic slash , this indicate all processed expand templates vm
			result = '/' + result;
		}

		result = super.includeEvent(result, currentResourcePath, directiveName);
		LOG.info("OUT:" + result);
		return result;
	}

}
